﻿using EWPlatAPP.FModels;
using EWPlatAPP.UControls;
using EWPlatAPP.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXIMEW.BLL;
using ZXIMEW.Models.DModels;

namespace EWPlatAPP
{
    public partial class FrmMain : FormParent
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        List<ModbusParaSetInfo> allList = new List<ModbusParaSetInfo>();
        RoleBLL roleBLL = new RoleBLL();
        ModbusParaBLL modbusParaBLL = new ModbusParaBLL();
        AlarmParaBLL aParaBLL = new AlarmParaBLL();
        StorageRegionBLL srBLL = new StorageRegionBLL();
        MenuBLL menuBLL = new MenuBLL();
        List<int> RoleIds = new List<int>();//角色Id集合
        FMainData mainInfo = null;//登录信息
        bool isAdmin = false;
        int userId = 0;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            if (this.Tag != null)
            {
                mainInfo = this.Tag as FMainData;
            }
            LoadLoginInfo();
            pSecondMenus.Visible = false;
            InitModbusParas();//初始化参数变量集合
            InitAlarmParas();//初始化报警参数集合
            InitReportParas();//初始化报表参数集合
            InitStorageList();//初始化存储区列表
            CreateModbusConn();//创建通信连接
            LoadMainItems();//加载主菜单列表
        }

        private void LoadLoginInfo()
        {
            if (mainInfo != null)
            {
                lblLoginUser.Text = mainInfo.LoginData.UserName;
                lblLoginTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                lblRightInfo.Text = "朝夕教育所有";
                userId = mainInfo.LoginData.UserId;
            }
            if (userId > 0)
            {
                //获取用户角色列表
                List<RoleInfo> roles = roleBLL.GetUserRoleList(userId);
                //角色编号集合
                RoleIds = roles.Select(x => x.RoleId).ToList();
                foreach (RoleInfo r in roles)
                {
                    if (r.IsAdmin)
                    {
                        isAdmin = true;
                        break;
                    }
                }
            }

        }

        /// <summary>
        /// 初始化参数变量集合
        /// </summary>
        private void InitModbusParas()
        {
            allList = modbusParaBLL.GetAllParas();

            //初始化实时变量集合
            //CommonHelper.CurrentParaAddress = modbusParaBLL.GetActualParaAddressList();
            var actualList = allList.Where(p => p.ParaName.Contains("Actual")).ToList();
            actualList.ForEach(p => CommonHelper.CurrentParaAddress.Add(p.ParaName, p));

            //初始化设置变量集合
            //CommonHelper.SetParaAddress = modbusParaBLL.GetSetParaAddressList();
            var setList = allList.Where(p => !p.ParaName.Contains("Actual")).ToList();
            actualList.ForEach(p => CommonHelper.SetParaAddress.Add(p.ParaName, p));
        }

        /// <summary>
        /// 报警参数集合初始化
        /// </summary>
        private void InitAlarmParas()
        {
            CommonHelper.AlarmParas = aParaBLL.GetAllAlarmParas();
        }

        /// <summary>
        /// 报表参数初始化
        /// </summary>
        private void InitReportParas()
        {
            CommonHelper.ReportParas = allList.Where(p => p.IsReport).ToList();
        }

        private void InitStorageList()
        {
            CommonHelper.StorageList = srBLL.GetStorageRegionList();
        }

        private void CreateModbusConn()
        {
            bool blOpen = CommonHelper.CreateSerialMaster();
            if (blOpen)
            {
                CommonHelper.OpenState = true;
            }
            if (!CommonHelper.OpenState)
            {
                MsgBoxHelper.MsgErrorShow("", "连接失败!");
                return;
            }
        }

        /// <summary>
        /// 主菜单加载 一级菜单 ----一个个按钮
        /// </summary>
        private void LoadMainItems()
        {
            //获取一级菜单列表
            List<MenuInfo> firstMenuList = menuBLL.GetFirstMenuList(RoleIds, isAdmin);
            if (firstMenuList.Count > 0)
            {
                //添加菜单项变成一个个按钮
                menuPanel.Controls.Clear();//清空控件
                int width = 100;
                int height = 30;
                int space = 25;
                int x = 30;
                int y = (menuPanel.Height - height) / 2;
                for (int i = 0; i < firstMenuList.Count; i++)
                {
                    Point location = new Point(x + i * (width + space), y);//按钮的位置
                    //创建按钮，并添加到控件中
                    menuPanel.Controls.Add(CreateMainMenuBtn(firstMenuList[i], location, new Size(width, height)));
                }
            }
        }

        //为主菜单创建主菜单按钮
        private UCircleButton CreateMainMenuBtn(MenuInfo mi, Point location, Size size)
        {
            UCircleButton btn = new UCircleButton();
            btn.BackColor = Color.WhiteSmoke;
            btn.BgColor = Color.RoyalBlue;
            btn.BgColor2 = Color.Transparent;
            btn.Font = new Font("微软雅黑 Light", 9F, FontStyle.Bold, GraphicsUnit.Point, 134);
            btn.ForeColor = Color.White;
            btn.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
            btn.SelectedColor = Color.Red;
            btn.Location = location;
            btn.Name = "mainBtn" + mi.MenuId;
            btn.Radius = 8;
            btn.Size = size;
            btn.Text = mi.MenuName;
            btn.Tag = mi;
            btn.Click += Btn_Click;
            return btn;
        }

        //一级按钮的响应
        //响应 1.子列表：加载二级菜单列表 2.打开相应的页面 3.执行一段程序代码
        private void Btn_Click(object sender, EventArgs e)
        {
            UCircleButton btn = sender as UCircleButton;
            FormHelper.SetSelectBtnFont(menuPanel, btn, Color.Red, Color.White);
            if (btn.Tag != null)
            {
                MenuInfo mi = btn.Tag as MenuInfo;
                if (mi != null)
                {
                    if (mi.MenuCode == "Exit")
                    {
                        //退出应用程序

                        //如果程序还在运行中，不能退出
                        if (CommonHelper.OpenState)
                        {
                            CommonHelper.serialMaster.Dispose();
                            CommonHelper.serialPort.Close();
                            CommonHelper.OpenState = false;
                        }
                        Application.Exit();
                    }
                    else
                    {
                        //获取二级子列表
                        List<MenuInfo> secMenuList = menuBLL.GetMenusByParentId(RoleIds, mi.MenuId, isAdmin);

                        //如果有子列表，加载；否则，就打开页面
                        if (secMenuList.Count > 0)
                        {
                            //加载二级列表
                            LoadSecondMenus(secMenuList);
                            pSecondMenus.Visible = true;
                        }
                        else
                        {
                            pSecondMenus.Visible = false;
                        }

                    }
                }
            }
        }

        /// <summary>
        /// 加载二级菜单
        /// </summary>
        /// <param name="subList"></param>
        private void LoadSecondMenus(List<MenuInfo> subList)
        {
            if (subList.Count > 0)
            {
                pSecondMenus.Controls.Clear();
                int width = 80, height = 24;
                int x = 30, y = (pSecondMenus.Height - height) / 2;
                for (int i = 0; i < subList.Count; i++)
                {
                    Point location = new Point(x + i * (width + 28), y);
                    //创建二级按钮并添加pSecondMenus中
                    pSecondMenus.Controls.Add(CreateSysMenuBtn(subList[i], location, new Size(width, height)));
                }
            }
        }

        private Control CreateSysMenuBtn(MenuInfo mi, Point location, Size size)
        {
            UCircleButton btn2 = new UCircleButton();
            btn2.BackColor = Color.White;
            btn2.BgColor = Color.White;
            btn2.BorderWidth = 1;
            btn2.BorderColor = Color.Gray;
            btn2.BgColor2 = Color.Transparent;
            btn2.SelectedColor = Color.Orange;
            btn2.Font = new Font("微软雅黑", 8F, FontStyle.Regular, GraphicsUnit.Point, 134);
            btn2.ForeColor = Color.Black;
            btn2.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
            btn2.SelectedColor = Color.Red;
            btn2.Location = location;
            btn2.Name = "sysBtn" + mi.MenuId;
            btn2.Radius = 3;
            btn2.Size = size;
            btn2.Text = mi.MenuName;
            btn2.UseVisualStyleBackColor = true;
            btn2.Tag = mi;
            btn2.Click += Btn2_Click;
            return btn2;
        }

        private void Btn2_Click(object sender, EventArgs e)
        {
            UCircleButton btn = sender as UCircleButton;
            //处理按钮的文字颜色
            FormHelper.SetSelectBtnFont(pSecondMenus, btn, Color.OrangeRed, Color.Black);
            //打开二级按钮的相关页面
            SecBtnClick(btn);
            FormHelper.ShowCloseBtn(mainPages, picClosePage);
        }

        private void SecBtnClick(Button btn)
        {
            if (btn.Tag != null)
            {
                MenuInfo menu = btn.Tag as MenuInfo;
                if (menu != null)
                {
                    ShowPage(menu);
                }
            }
        }

        /// <summary>
        /// 显示页面
        /// </summary>
        private void ShowPage(MenuInfo menu)
        {
            string assName = this.GetType().Assembly.GetName().Name;
            if (!string.IsNullOrEmpty(menu.FrmName) && !menu.FrmName.Contains(assName))
            {
                menu.FrmName = assName + "." + menu.FrmName;
            }

            LoginUserModel loginUser = new LoginUserModel() { IsAdmin = isAdmin, UserRoleIds = RoleIds };
            if (menu.IsTop)
            {
                if (menu.MenuName == "修改密码")
                {
                    FormHelper.ShowForm(menu.FrmName, mainInfo, this);
                }
                else
                {
                    FormHelper.ShowForm(menu.FrmName, loginUser, this);
                }
            }
            else
            {
                //添加到TabPage页
                FormHelper.AddFormToTabPage(mainPages, menu.FrmName, loginUser);

                //关闭按钮是否显示
                FormHelper.ShowCloseBtn(mainPages, picClosePage);
            }
        }

        /// <summary>
        /// 关闭TabPage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picClosePage_Click(object sender, EventArgs e)
        {
            TabPage selTab = mainPages.SelectedTab;
            mainPages.TabPages.Remove(selTab);
            //关闭Form ---显示在TabPage页中
            FormHelper.CloseOpenForm(selTab.Name);
            FormHelper.ShowCloseBtn(mainPages, picClosePage);
        }

        private void mainPages_SizeChanged(object sender, EventArgs e)
        {
            FormHelper.TabControl_SizeChanged(sender, e);
        }
    }
}
